package control.file;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import book.SetsBook;

import addon.Text;



public class FileBook {

	SetsBook book = new SetsBook();
	List<SetsBook> listbook;
private String route = "src\\huges";
	public FileBook(){

		listbook = new ArrayList<>();
		File file = new File(route);
		String[] list = file.list();
		if (list != null) {
			String nameBook = "";
			String autorBook = "";
			for (String absolutName : list) {
				for (int i = 0; i < absolutName.length(); i++) {

					while (absolutName.charAt(i) != '.') {
						nameBook += absolutName.charAt(i);
						i++;
					}
					i++;
					while (absolutName.charAt(i) != '.') {
						autorBook += absolutName.charAt(i);
						i++;
					
					}
					i++;
					while (i < absolutName.length()) {
						i++;

					}
				}

				SetsBook book = new SetsBook();				
				book.setName(nameBook);
				book.setAutor(autorBook);
				 nameBook = "";
				 autorBook = "";
				
				
				@SuppressWarnings("unused")
				String nameNewBook = route;
				
				nameNewBook += "\\" + book.getName() + "." + book.getAutor()
						+ ".txt";
				
				listbook.add(book);
			}
		}
		
	}
	
	public void addFile(){
		SetsBook book = new SetsBook();
		String nameNewBook = route;
        System.out.println("Name: ");
		
		book.setName(Text.input());
		System.out.println("Autor");
		
		book.setAutor(Text.input());
		listbook.add(book);
		
		
		nameNewBook += "\\" + book.getName() + "." + book.getAutor()
				+ ".txt";
		
		File file = new File(nameNewBook);		
		
		
		try {
			file.createNewFile();
			System.out.println("Add success");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void deleteFile(){
SetsBook setbook = new SetsBook();
        System.out.println("Name: ");
		setbook.setName(Text.input()) ;
		
		System.out.println("Autor");
		setbook.setAutor(Text.input());
		
		String nameNewBook = route;
		nameNewBook += "\\" + setbook.getName() + "." + setbook.getAutor() + ".txt";
		File file = new File(nameNewBook);
		file.delete();  
		for(SetsBook books : listbook)
		if(books.equals(setbook))	{
			listbook.remove(setbook);
        System.out.println("Delete success");}
		else 
	        System.out.println("Book not found");
  }
	
public void listFile(){

for(SetsBook books : listbook)
		System.out.println(books);
if (listbook.size() == 0) System.out.println("list is empty");
	
}
}

